#include <glib-2.0/glib.h>
#include <netdb.h>

#include "nio.h"

#define WON_PORT 5556 

int
network_do_login(char *user,
				 char *pass)
{
	char buf[128];
	char *buf_resp;
	char flags;

	sprintf(buf, "LOGIN %s %s", user, pass);
	if (nio_send(buf, strlen(buf) + 1, 0) != 0)
		return -1;
	if (nio_recv(&buf_resp, &flags) < 1)
		return -1;
	
	if (strcmp(buf_resp, "LNACK") == 0) /* Login rejected */
		return 1; 
	else if (strcmp(buf_resp, "LACK") == 0) /* Login succeded. */
		return 0;

	return -1; /* Unknown error. */
}

int
network_login(char *host,
			  char *user,
			  char *pass)
{
	int sd, ret;
	struct sockaddr_in addr;
	struct hostent *he;

	nio_init();

	if ((he = gethostbyname(host)) == NULL)
		return -1;

	sd = socket(PF_INET, SOCK_STREAM, 0);
	
	addr.sin_family = AF_INET;
	addr.sin_port = htons(WON_PORT);
	addr.sin_addr = *((struct in_addr *)he->h_addr);
	memset(addr.sin_zero, 0, sizeof(addr.sin_zero));

	if (connect(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
		return -2;


	gnutls_transport_set_ptr(nio_session, (gnutls_transport_ptr_t)sd);

	/* Perform the TLS handshake */
	ret = gnutls_handshake(nio_session);

	if (ret < 0) {
		g_print("*** Handshake failed\n");
		gnutls_perror (ret);
		return -3;
	} else
		g_print("- Handshake was completed\n");
	
	if (network_do_login(user, pass) != 0)
		return -4;

	return 0;
}

gpointer
network_main_thread(gpointer data)
{
	void *buffer;
	size_t len;
	char flags;
	while (1) {
		len = nio_recv(&buffer, &flags);
		if (len < 1) {
			g_print("network_main_thread(): error recieving data\n");
			break;
		}
	}
}

